package com.lyw.GeoLocationClient.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;
import com.SDKReceiver;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.easemob.applib.utils.HXPreferenceUtils;
import com.lyw.GeoLocationClient.App;
import com.lyw.GeoLocationClient.R;
import com.lyw.GeoLocationClient.utils.IconManager;
import com.lyw.GeoLocationClient.utils.TimeUtil;
import com.lyw.GeoLocationClient.utils.UICallback;
import com.lyw.GeoLocationClient.bean.BmobUser;
import com.lyw.GeoLocationClient.json.Poi;
import com.lyw.GeoLocationClient.json.res.PoiList;
import com.lyw.GeoLocationClient.service.BmobUserAdapter;
import com.lyw.GeoLocationClient.service.LBSClient;
import retrofit.Callback;
import retrofit.RetrofitError;
import timber.log.Timber;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class MapActivity extends Activity
        implements BaiduMap.OnMapClickListener, View.OnClickListener,
        RouteLinePlayer.RouteLinePlayerCallback, BaiduMapUtils.OnMarkerClickListener{
    private static final String TITLE = "title";

    private static final int UPDATE_USER_LIST = 0;
    private static final int UPDATE_GEOFANCE = 1;
    private static int LIMIT_DAYS = 0;

    private static int UPDATE_LIST_TIME = 100 * 60 * 1000;
    private static int UPDATE_MAP_TIME = 5 * 1000;
    private static final String LIST = "list";
    private IconManager iconManager;
    private boolean firstRun = true;


    private String mContentText;
    private TextView mContentTextView;
    private LBSClient mClient;

    private View mNetErrorView;
    private TextView mTitleNameView;
    private ImageView mTitleStatusView;
    private ProgressBar mTitleProgressBar;

    private Button mSetGeofance;
    private Button mSaveGeofance;
    private Button mCancel;
    private ImageButton mPlayRoute;

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private Menu mMenu;
    private ProgressDialog progressDialog;

    private SDKReceiver mReceiver;
    private Timer mUpdateListTimer;
    private Timer mUpdateMapTimer;

    private LinkedList<LatLng> mClickPoint;
    private HashMap<String , List<Poi>> mItemPoiList;
    private ArrayList<String> mMembers;
    BmobUserAdapter mBmobUserAdapter;
    private ArrayList<BmobGeoPoint> mGeofanceList;
    private ArrayList<Poi> mPoiList;
    private ArrayList<BmobUser> mBmobUsers;
    private BmobUser mSelectedUser;
    private HashMap<String, GeotableItem> mGeoMap = new HashMap<String, GeotableItem>();
    private HashMap<String, List<Overlay>> mOverlayMap = new HashMap<String, List<Overlay>>();

    BaiduMapUtils mapUtils;
    RouteLinePlayer mRoutePlayer;

    private boolean isGroup = false;

    private boolean mNeedUpdateMapStatus = true;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_USER_LIST:
                    break;
                case UPDATE_GEOFANCE:
                    drawGeofance();
                default:
                    break;
            }
        }
    };

    private UICallback uiCallback = new UICallback() {
        @Override
        public void onUpdateUserData() {
            mHandler.sendEmptyMessage(UPDATE_USER_LIST);
        }

        @Override
        public void onReceiveLocation(BDLocation location) {
            LOG("receive location " + location.getLongitude() + " " + location.getLatitude());
            if (!App.isAdmin()) {
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        .direction(location.getDirection()).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);

                drawLoadTrack(mClient.getLocationList());
            }
        }
    };

    public static void showInMap(Context context, ArrayList<String> list, String title) {
        Intent intent = new Intent(context, MapActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putStringArrayListExtra(LIST, list);
        intent.putExtra(TITLE, title);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle inState) {
        super.onCreate(inState);
        App.getInstance().addActivity(this);
        mClient = LBSClient.getInstance();
        mBmobUserAdapter = new BmobUserAdapter(this);
        iconManager = IconManager.getInstance();
        iconManager.reset();

        setContentView(R.layout.admin_activity);
        createViews();
        initData();
        initViews();

        String title = getString(R.string.app_name);

        mMembers = getIntent().getStringArrayListExtra(LIST);
        if (mMembers == null || mMembers.size() == 0) {
            Timber.e("member is null!");
            finish();
        }
        if (mMembers.size() > 1) {
            isGroup = true;
        }
        title = getIntent().getStringExtra(TITLE);
        Timber.d("get members " + mMembers.toString());

        if (mClient != null) {
//            mClient.loadTableList();
            mClient.addUICallback(uiCallback);
        }

        for (String s : mMembers) {
            getUser(s);
        }

        if (isGroup) {
            getGroup(title);
        }

        mTitleNameView.setText(title);

        // 注册 SDK 广播监听者
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);

        LIMIT_DAYS = HXPreferenceUtils.getInstance().getTracDays();
        int span = HXPreferenceUtils.getInstance().getUpdateSpan();
        if (span < 3) {
            span = 3;
        }
        UPDATE_MAP_TIME = span * 1000;
    }

    private void createViews() {
        mMapView =  (MapView) findViewById(R.id.mapView);
        progressDialog = new ProgressDialog(this);
        mNetErrorView = findViewById(R.id.net_status_bar_top);

        mPlayRoute = ((ImageButton) findViewById(R.id.btn_play_route));

        mTitleNameView = (TextView) findViewById(R.id.ivTitleName);
        mTitleProgressBar = (ProgressBar) findViewById(R.id.ivTitleProgress);
        mTitleStatusView = (ImageView) findViewById(R.id.ivTitleStatus);
        mTitleNameView.setOnClickListener(this);

        mSetGeofance = (Button) findViewById(R.id.btn_set_geofance);
        if (!App.isAdmin()) {
            mSetGeofance.setVisibility(View.GONE);
        }
        mSaveGeofance = (Button) findViewById(R.id.btn_save);
        mCancel = (Button) findViewById(R.id.cancel);
        mSetGeofance.setOnClickListener(this);
        mSaveGeofance.setOnClickListener(this);
        mCancel.setOnClickListener(this);
    }

    private void initData() {
        mBmobUsers = new ArrayList<BmobUser>();
        if (mGeofanceList == null) {
            mGeofanceList = new ArrayList<BmobGeoPoint>();
        }
        mClickPoint = new LinkedList<LatLng>();
        mItemPoiList = new HashMap<String, List<Poi>>();
    }

    private void initViews() {
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);


        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();
        MapStatusUpdate st = MapStatusUpdateFactory.newLatLngZoom(new LatLng(119.330221,26.047125), 12.0f);
        mBaiduMap.setMapStatus(st);
        mBaiduMap.setOnMapClickListener(this);

        mBaiduMap.setMyLocationEnabled(true);
        mapUtils = new BaiduMapUtils(this, mBaiduMap);
        mRoutePlayer = mapUtils.getRoutePlayer();

        mapUtils.setRouteLinePlayerCallback(this);

        mPlayRoute.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                mRoutePlayer.stop();
                mPlayRoute.setVisibility(View.GONE);

                return true;
            }
        });

        mapUtils.setOnMarkerClickListener(this);

        if (!App.isAdmin()) {
            mapUtils.animateUserStatus();
        }
    }


    private void showMapWithLocationClient() {
        LocationClient client = new LocationClient(this);
        client.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (mNeedUpdateMapStatus) {
                    LatLng llA = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());

                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(llA, 17.0f);
                    mBaiduMap.animateMapStatus(u);
                }
            }
        });

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); //设置坐标类型

        option.setScanSpan(0);
        option.setIsNeedAddress(true);
        client.setLocOption(option);
    }

    private void drawTrack(LinkedList<BDLocation> locations) {
        List<LatLng> list = new ArrayList<LatLng>();
        for (BDLocation lo : locations) {
            LatLng latLng = new LatLng(lo.getLatitude(), lo.getLongitude());
            list.add(latLng);
        }

        boolean isOut = mClient.isOutOfGeofance();

        int color = getResources().getColor(R.color.darkgreen);
        if (isOut) {
            color = getResources().getColor(R.color.red);
        }
        OverlayOptions ooPolyline = new PolylineOptions().width(10)
                .color(color).points(list);
        mBaiduMap.addOverlay(ooPolyline);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // activity 暂停时同时暂停地图控件
        mMapView.onPause();
    }

    private void showProgress(String msg) {
        progressDialog.setMessage(msg);
        progressDialog.show();
    }


    private void hideProgress() {
        if (progressDialog != null
                && progressDialog.isShowing())
            progressDialog.cancel();
    }

    private void drawGeofance() {
        LinkedList<LatLng> list = new LinkedList<LatLng>();
        if (mGeofanceList == null) {
            return;
        }
        for (BmobGeoPoint poi : mGeofanceList) {
            LatLng l = new LatLng(poi.getLatitude(), poi.getLongitude());
            list.add(l);
        }

        Stroke stroke = new Stroke(list.size(), getResources().getColor(R.color.lightblue));
        int color = getResources().getColor(R.color.lightbluealpha);
        mapUtils.drawGeofanceOnMap(list, stroke, color);
    }


    private void setGeofence() {
        mSetGeofance.setVisibility(View.GONE);
        mSaveGeofance.setVisibility(View.VISIBLE);
        mCancel.setVisibility(View.VISIBLE);

//        mBaiduMap.clear();
        if (mClickPoint == null) {
            mClickPoint = new LinkedList<LatLng>();
        } else {
            mClickPoint.clear();
        }

    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (mSaveGeofance.getVisibility() == View.VISIBLE) {
            mClickPoint.add(latLng);
            BitmapDescriptor bd = BitmapDescriptorFactory
                    .fromResource(R.drawable.icon_gcoding);
            OverlayOptions ooB = new MarkerOptions().position(latLng).icon(bd)
                    .zIndex(mClickPoint.size());
            mBaiduMap.addOverlay(ooB);

            if (mClickPoint.size() > 1) {
                OverlayOptions ooPolyline = new PolylineOptions()
                        .width(10)
                        .color(this.getResources().getColor(R.color.lightblue))
                        .points(mClickPoint);
                mBaiduMap.addOverlay(ooPolyline);
            }
        }

        mBaiduMap.hideInfoWindow();

    }

    private void exitGeofenceEdit(boolean clearMap) {
        mSetGeofance.setVisibility(View.VISIBLE);
        mSaveGeofance.setVisibility(View.GONE);
        mCancel.setVisibility(View.GONE);

        mBaiduMap.setOnMapClickListener(null);
        mClickPoint.clear();
        if (clearMap) {
            mBaiduMap.clear();
            firstRun = true;
        }
//        mHandler.post(new UpdateMapTask());
    }

    private boolean saveGeofance() {
        if (mClickPoint.size() > 2) {
            mGeofanceList.clear();
            for (LatLng latLng : mClickPoint) {
                BmobGeoPoint point = new BmobGeoPoint(latLng.longitude, latLng.latitude);
                mGeofanceList.add(point);
            }

            mClient.saveGeofance(mSelectedUser, mGeofanceList);
            return true;
        }
        return false;
    }

    private void drawItemList() {
        Iterator iter = mItemPoiList.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            mHandler.post(new UpdateItemRun((String)key, (ArrayList<Poi>) val));
        }
    }

    private void drawLoadTrack(LinkedList<BDLocation> locationList) {
        if (locationList == null) {
            return;
        }
        ArrayList<Poi> list = new ArrayList<Poi>();
        for (BDLocation location : locationList) {
            Poi p = new Poi(location.getLongitude(), location.getLatitude());
            p.setCreate_time(location.getTime());
            p.setAddress(location.getAddrStr());
            list.add(p);
        }
        mHandler.post(new UpdateItemRun(mSelectedUser.getUsername(), list));
    }

    @Override
    protected void onResume() {
        super.onResume();
        // activity 恢复时同时恢复地图控件
        mMapView.onResume();
        if (!App.isAdmin()) {
            mNeedUpdateMapStatus = true;
        }
        if (App.isAdmin() && firstRun) {
            showProgress("");
            mHandler.post(new UpdateMapTask());
//
            startUpdate();
        }
    }

    private void startUpdate() {
        if (mUpdateMapTimer != null) {
            mUpdateMapTimer.cancel();
        }
        mUpdateMapTimer = new Timer();
        mUpdateMapTimer.schedule(new UpdateMapTask(), 0, UPDATE_MAP_TIME);
    }

    private void stopUpdate() {
        if (mUpdateMapTimer != null) {
            mUpdateMapTimer.cancel();
        }
        mUpdateMapTimer = null;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ivTitleName:
//                if (isConnected())
//                    showStatusQuickAction(v);
                break;
            case R.id.btn_set_geofance:
                setGeofence();

                break;
            case R.id.btn_save:
                if (saveGeofance()) {
                    exitGeofenceEdit(true);
                    drawGeofance();
                    drawItemList();
                }
                break;
            case R.id.cancel:
                exitGeofenceEdit(false);

                break;

            default:
                break;
        }

    }


    @Override
    public void onRouteStart() {
        stopUpdate();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mSetGeofance.setVisibility(View.GONE);
                mPlayRoute.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onRoutePause() {
        Timber.d("onRoutePause");
    }

    @Override
    public void onRouteStop() {
        Timber.d("onRouteStop");

        startUpdate();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mSetGeofance.setVisibility(View.VISIBLE);
                mPlayRoute.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onRouteProgress(int index, int total) {
        Timber.d("on Progress " + index + " " + total);
    }

    public void onPlayBtnClick(View view) {
        if (mRoutePlayer.isPlaying()) {
            mRoutePlayer.pause();
            mPlayRoute.setImageResource(R.drawable.ic_av_play_circle_outline);
        } else {
            mRoutePlayer.play();
            mPlayRoute.setImageResource(R.drawable.ic_av_pause_circle_outline);
        }
    }



    @Override
    public void onMarkClick(Marker marker, String name) {
        stopUpdate();
    }

    class UpdateMapTask extends TimerTask {

        @Override
        public void run() {
            LOG("run task UpdateMapTask");
            if (firstRun) {
                firstRun = false;
                mHandler.sendEmptyMessage(UPDATE_GEOFANCE);
            }

//            mapUtils.clearOldData();
//            mBaiduMap.clear();
            for (String name : mMembers) {
                final String n =  name;
                mClient.getPoiList(name, new Callback<PoiList>() {
                    @Override
                    public void success(PoiList poiList, retrofit.client.Response response) {
                        if (poiList != null) {
                            mHandler.post(new UpdateItemRun(n, poiList.pois));
                        }
                    }

                    @Override
                    public void failure(RetrofitError retrofitError) {

                    }
                });
            }
        }
    }

    private void getGroup(String title) {
        mBmobUserAdapter.queryBmobUser(title, new FindListener<BmobUser>() {
            @Override
            public void onSuccess(List<BmobUser> list) {
                if (list != null && list.size() > 0) {
                    Timber.d("get group size " + list.size());
                    Timber.d(list.toString());

                    if (isGroup) {
                        mSelectedUser = list.get(0);
                        Timber.d("get group " + mSelectedUser);
                        if (mGeofanceList == null) {
                            mGeofanceList = new ArrayList<BmobGeoPoint>();
                        }
                        mGeofanceList.clear();
                        if (mSelectedUser.getGeofance() != null) {
                            mGeofanceList.addAll(mSelectedUser.getGeofance());
                            mHandler.sendEmptyMessage(UPDATE_GEOFANCE);
                        }
                    }
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    private void getUser(final String user) {
        mBmobUserAdapter.queryBmobUser(user, new FindListener<BmobUser>() {
            @Override
            public void onSuccess(List<BmobUser> list) {
                if (list != null && list.size() > 0) {
                    Timber.d("get users size " + list.size());
                    mBmobUsers.add(list.get(0));
                    if (!isGroup) {
                        mSelectedUser = mBmobUsers.get(0);
                        if (mGeofanceList == null) {
                            mGeofanceList = new ArrayList<BmobGeoPoint>();
                        }
                        mGeofanceList.clear();
                        if (mSelectedUser.getGeofance() != null) {
                            mGeofanceList.addAll(mSelectedUser.getGeofance());
                            mHandler.sendEmptyMessage(UPDATE_GEOFANCE);
                        }
                    }

                    GeotableItem item = new GeotableItem();
                    item.setName(list.get(0).getUsername());
                    item.setTitle(list.get(0).getName());
                    item.mColor = (iconManager.getColor(mBmobUsers.size()));
                    item.mIconRes = iconManager.getIcon(mBmobUsers.size());
                    mGeoMap.put(user, item);

                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    class UpdateItemRun implements Runnable {
        String id;
        ArrayList<Poi> pois;
        public UpdateItemRun(String id, ArrayList<Poi> pois) {
            this.id = id;
            this.pois = pois;
        }

        @Override
        public void run() {
            Timber.d("RUN TASK UpdateItemRun");
            if (pois != null && pois.size() > 0) {
                List<Poi> result;
                if (LIMIT_DAYS > 0) {
                    result = verifyPoiByTime(LIMIT_DAYS, pois);
                } else {
                    result = pois;
                }

                List<Poi> old = mItemPoiList.get(id);
                if (old != null && old.size()  == result.size()) {
                    Timber.d("same poi for " + id);
                } else {
                    mItemPoiList.put(id, result);
                    updateItemView(id, result);
                }

            }
            hideProgress();
        }
    }

    private List<Poi> verifyPoiByTime(int day, List<Poi> list) {
        List<Poi> result = new ArrayList<Poi>();

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date limit = TimeUtil.getDaysFromNow(day);

        for (int i = 0; i < list.size(); i++) {
            Poi poi = list.get(i);
            try {
                Date dt = df.parse(poi.getCreate_time());
                if (limit.getTime() < dt.getTime()) {
                    result.add(poi);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        Timber.d("return size " + result.size());
        return result;
    }

    public void updateItemView(String id, List<Poi> pois) {
//        GeotableItem geotableItem = mClient.getGeotableMap().get(id);

        GeotableItem geotableItem = mGeoMap.get(id);
        if (geotableItem != null) {
            LOG("updateItemView " + geotableItem.getName() + " " + pois.size());
            double[] last_lo = new double[2];//记录最后一点
            LinkedList<LatLng> pts = new LinkedList<LatLng>();

            Poi lastPoi = null;
            long diff_max_time = 6*60*60*1000;//6h

            List<Overlay> oldOverlays = mOverlayMap.get(id);
            ArrayList<Overlay> oldOverlaysArray = null;
            if (oldOverlays != null && oldOverlays.size() > 0) {
                oldOverlaysArray = new ArrayList<Overlay>(mOverlayMap.get(id));
                oldOverlays.clear();
            }
            mapUtils.clearMarker(geotableItem.getName());

            for (int i = pois.size() -1 ; i >=0; i--) {
                Poi p = pois.get(i);
                LatLng pt = new LatLng(p.getLocation()[1], p.getLocation()[0]);

                if (lastPoi != null) {
                    try {
                        Date pDate = TimeUtil.parsePoiCreateTime(p.getCreate_time());
                        Date lDate = TimeUtil.parsePoiCreateTime(lastPoi.getCreate_time());

                        long diff = pDate.getTime() - lDate.getTime();
                        if (diff < diff_max_time && i != 0) {
                            pts.add(pt);
                        } else {
                            if (i == 0) {
                                pts.add(pt);
                            }
                            Overlay overlay = mapUtils.drawTrackOverlay(geotableItem, pts, geotableItem.getColor());

                            pts.clear();
                            pts.add(pt);
                            if (overlay != null) {
                                mapUtils.drawTime(pt, p.getCreate_time());
                                if (mOverlayMap.get(id) == null) {
                                    mOverlayMap.put(id, new ArrayList<Overlay>());
                                }
                                mOverlayMap.get(id).add(overlay);
                            }
                        }

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (i == 0) {
                        mapUtils.drawTime(pt,p.getCreate_time());
                    }
                }

                lastPoi = p;
            }

            Poi poi = pois.get(0);
            last_lo= poi.getLocation();
            if (isGroup) {
                boolean isInGeofance = mClient.isPointInGeofance(last_lo[1], last_lo[0]);
                if (!isInGeofance) {
                    notifyOutOfGeofance(geotableItem.getGeoId(), geotableItem.getTitle(), poi.getAddress());
                }
            }


            if (
                    last_lo[0] != 0 && last_lo[1] != 0) {
                MyLocationData locData = null;
                locData = new MyLocationData.Builder()
                        .direction(100)
                        .latitude(last_lo[1])
                        .longitude(last_lo[0])
                        .build();
                if (!isGroup) {

                    mBaiduMap.setMyLocationData(locData);
                }

                if (mNeedUpdateMapStatus) {
                    LatLng ll = new LatLng(locData.latitude,
                            locData.longitude);
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 18.0f);
                    mBaiduMap.animateMapStatus(u);
                    mNeedUpdateMapStatus = false;
                }
            }

            //clear old overlays
            if (oldOverlaysArray != null) {
                for (Overlay overlay : oldOverlaysArray) {
                    overlay.remove();
                }
            }
        }
    }


    private void notifyOutOfGeofance(int geotable_id, String name, String lastAddr) {
        LOG("notify " + geotable_id + " name " + name);
        NotificationHelper.getInstance(this).notifyItemOutOfGeofance(geotable_id, name, lastAddr);
    }

    //更新用户轨迹
//    class UpdatePoiHandler extends HttpResponseHandler {
//        private String id;
//        public UpdatePoiHandler(String id) {
//            this.id = id;
//        }
//
//        @Override
//        protected void onSuccess(Response res, HttpStatus status, NameValuePair[] headers) {
//            PoiList respon = res.getObject(PoiList.class);
//            if (respon!= null && respon.status == 0) {
//                if (respon.pois != null && respon.pois.size() > 0) {
//                    LOG("get pois of " + id);
////                    mPoiListMap.put(id, respon.pois);
//                    mHandler.post(new UpdateItemRun(id, respon.pois));
//                }
//            }
//        }
//
//        @Override
//        protected void onFailure(Response res, HttpException e) {
//
//        }
//    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mUpdateListTimer != null) {
            mUpdateListTimer.cancel();
        }

        if (mUpdateMapTimer != null) {
            mUpdateMapTimer.cancel();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消监听 SDK 广播
        unregisterReceiver(mReceiver);
        mClient.addUICallback(null);
    }

    public void LOG(String msg) {
        Timber.d(msg);
    }



}
